import SolidTooltip from "@lib/Tooltip";
import { splitProps, mergeProps, createMemo, Index } from "solid-js";
import type { TableHeaderProps } from "./types";

const defaultTableHeaderProps: Partial<TableHeaderProps<any>> = {
    columns: [],
};

const TableHeader = <T = {},>(p: TableHeaderProps<T>) => {
    const [local, attributes] = splitProps(
        mergeProps(defaultTableHeaderProps, p),
        ["columns", "fixed", "classList", "style"]
    );

    const mapped = createMemo(() => {
        return local.columns?.map((col) => {
            return {
                ...col,
                classList: {
                    "text-start": col.headerAlign === "start",
                    "text-center": col.headerAlign === "center",
                    "text-end": col.headerAlign === "end",
                    ...col?.classList,
                },
            };
        });
    });

    return (
        <thead
            classList={{ fixed: local.fixed, ...local.classList }}
            style={local.style}
        >
            <tr>
                <Index each={mapped()}>
                    {(column, index) =>
                        column().tooltip ? (
                            <SolidTooltip
                                as="th"
                                {...attributes}
                                style={column().style}
                                classList={{ ...column().classList }}
                                title={column().label ?? column().name}
                            >
                                {column().label ?? column().name}
                            </SolidTooltip>
                        ) : (
                            <th
                                {...attributes}
                                style={column().style}
                                classList={{ ...column().classList }}
                            >
                                {column().label ?? column().name}
                            </th>
                        )
                    }
                </Index>
            </tr>
        </thead>
    );
};

export default TableHeader